<script setup>
import * as echarts from 'echarts';
import {onMounted, ref, nextTick, defineProps} from "vue";
import {getVisionChartData} from "@/api/eyeCare.js";

const echartRef = ref(null);

const props = defineProps({
  patientId: String
})

onMounted(async () => {
  const chart = echarts.init(echartRef.value);
  if (echartRef.value) {
    const resp = await getVisionChartData(10, props.patientId)
    let leftData = []
    let rightData = []

    resp.data.forEach(item => {
      if (item.type === 1) {
        leftData.push([item.healTime, item.ocularAxis])
      } else {
        rightData.push([item.healTime, item.ocularAxis])
      }
    })
    chart.setOption({
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: ['左眼视力', '右眼视力']
      },
      xAxis: {
        type: 'time',
        boundaryGap: false, // 防止坐标轴两边留白
        minInterval: 'auto', // 自动设置最小间隔，根据数据量自动调整
        splitLine: {
          show: false // 是否显示分割线
        },
        axisLabel: {
          formatter: function (value) {
            // 根据时间跨度自定义格式化
            const dateStr = echarts.format.formatTime('yyyy-MM-dd HH:mm', value);
            const hasData = [...leftData, ...rightData].some(
                item => echarts.format.formatTime('yyyy-MM-dd HH:mm', item[0]) === dateStr
            );
            return hasData ? echarts.format.formatTime('yyyy-MM-dd', value) : '';
          }
        }
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          data: leftData,
          type: 'line',
          smooth: true,
          name: "左眼视力"
        },
        {
          data: rightData,
          type: 'line',
          smooth: true,
          name: "右眼视力"
        }
      ]
    })
    await nextTick()
    chart.resize()
  }
})

</script>

<template>
  <div class="chart-container">
    <div ref="echartRef" style="width: 100%;height: 25rem"/>
  </div>

</template>

<style scoped lang="scss">
.chart-container {
  padding: 16px
}
</style>